package com.sunhao.springboot_satoken.exception;

import com.sunhao.springboot_satoken.utils.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import org.hibernate.validator.internal.engine.ConstraintViolationImpl;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 全局异常处理类
 * 处理系统中的其他异常
 * @author SunHao
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理参数校验异常（@Valid注解校验失败）
     * @param e 参数校验异常
     * @return 响应结果
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("参数校验异常: {}", e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return new Response("400", "参数校验失败", errorMap);
    }

    /**
     * 处理参数绑定异常
     * @param e 参数绑定异常
     * @return 响应结果
     */
    @ExceptionHandler(BindException.class)
    public Response handleBindException(BindException e) {
        log.error("参数绑定异常: {}", e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return new Response("400", "参数绑定失败", errorMap);
    }

    /**
     * 处理约束违反异常
     * @param e 约束违反异常
     * @return 响应结果
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Response handleConstraintViolationException(ConstraintViolationException e) {
        log.error("约束违反异常: {}", e.getMessage());
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        Map<String, String> errorMap = new HashMap<>();
        for (ConstraintViolation<?> violation : violations) {
            String path = violation.getPropertyPath().toString();
            String field = path.substring(path.lastIndexOf(".") + 1);
            errorMap.put(field, violation.getMessage());
        }
        return new Response("400", "参数约束违反", errorMap);
    }

    /**
     * 处理业务异常
     * @param e 业务异常
     * @return 响应结果
     */
    @ExceptionHandler(BusinessException.class)
    public Response handleBusinessException(BusinessException e) {
        log.error("业务异常: {}", e.getMessage());
        return new Response(e.getCode(), e.getMessage(), null);
    }

    /**
     * 处理其他未知异常
     * @param e 未知异常
     * @return 响应结果
     */
    @ExceptionHandler(Exception.class)
    public Response handleException(Exception e) {
        log.error("系统异常: {}", e.getMessage(), e);
        return new Response("500", "系统异常，请联系管理员", null);
    }
}